package com.hjq.fcloud.ui.activity

import android.view.*
import android.view.inputmethod.EditorInfo
import android.widget.*
import android.widget.TextView.OnEditorActionListener
import com.hjq.fcloud.R
import com.hjq.fcloud.aop.SingleClick
import com.hjq.fcloud.app.AppActivity
import com.hjq.fcloud.http.api.GetCodeApi
import com.hjq.fcloud.http.api.LoginApi
import com.hjq.fcloud.http.model.HttpData
import com.hjq.fcloud.manager.InputTextManager
import com.hjq.fcloud.ui.dialog.RightAlertDialog
import com.hjq.fcloud.utils.AppConfigUtils
import com.hjq.http.EasyHttp
import com.hjq.http.listener.HttpCallback
import com.hjq.widget.view.CountdownView
import com.hjq.widget.view.SubmitButton
import okhttp3.Call


class LoginActivity : AppActivity(), OnEditorActionListener {

    private val phoneView: EditText? by lazy { findViewById(R.id.phoneEt) }
    private val codeView: EditText? by lazy { findViewById(R.id.codeEt) }
    private val countdownView: CountdownView? by lazy { findViewById(R.id.cv_password_forget_countdown) }
    private val commitView: SubmitButton? by lazy { findViewById(R.id.loginBtn) }
    private val checkBoxView: ImageView? by lazy { findViewById(R.id.checkBoxView) }
    private val checkBoxParentView: View? by lazy { findViewById(R.id.checkBoxParentView) }
    private var mUserAgreement: View? = null
    private var mPrivateAgreement: View? = null

    private var isAgree: Boolean = false
    private var sendtoken:String? = null

    override fun getLayoutId(): Int {
        return R.layout.login_activity
    }

    override fun initView() {
        codeView?.setOnEditorActionListener(this)
        commitView?.let {
            InputTextManager.with(this)
                .addView(phoneView)
                .addView(codeView)
                .setAlpha(true)
                .setMain(it)
                .build()
        }

        mUserAgreement = findViewById(R.id.tv_user_agreement)
        mPrivateAgreement = findViewById(R.id.tv_privacy_agreement)
        checkBoxParentView?.setOnClickListener {
            isAgree = !isAgree
            if(isAgree){
                checkBoxView?.setBackgroundResource(R.mipmap.ic_login_check)
            }else{
                checkBoxView?.setBackgroundResource(R.mipmap.ic_login_uncheck)
            }
        }
        setOnClickListener(countdownView, commitView, mUserAgreement, mPrivateAgreement)
        phoneView?.setText(AppConfigUtils.phone)
    }

    override fun initData() {}

    @SingleClick
    override fun onClick(view: View) {
        if (view === countdownView) {
            sendCode()
        } else if (view === commitView) {
            if (!isAgree) {
                toast("请勾选阅读协议")
                commitView?.reset()
                return
            }
            login()
        } else if (view == mPrivateAgreement) {
            RightAlertDialog.processHyperLinkClick(this, true)
        } else if (view == mUserAgreement) {
            RightAlertDialog.processHyperLinkClick(this, false)
        }
    }

    private fun sendCode() {
        if (phoneView?.text.toString().length == 0) {
            toast(R.string.common_phone_input_error)
            return
        }

        // 隐藏软键盘
        hideKeyboard(currentFocus)

        requestSendCode()
    }

    private fun requestSendCode() {
        // 获取验证码
        EasyHttp.post(this)
            .api(GetCodeApi().apply {
                setPhone(phoneView?.text.toString())
            })
            .request(object : HttpCallback<HttpData<GetCodeApi.DataJson?>>(this) {
                override fun onSucceed(data: HttpData<GetCodeApi.DataJson?>) {
                    toast(R.string.common_code_send_hint)
                    sendtoken = data?.getData()?.sendtoken
                    countdownView?.start()
                }
            })
    }

    private fun login() {
        if (phoneView?.text.toString().length == 0) {
            toast(R.string.common_phone_input_error)
            commitView?.reset()
            return
        }

        if (codeView?.text.toString().length == 0) {
            toast(R.string.common_code_error_hint)
            commitView?.reset()
            return
        }

        requestLogin()
    }

    private fun requestLogin() {
        var api = LoginApi()
            .setPhone(phoneView?.text.toString().trim())
            .setCode(codeView?.text.toString().trim())
            .setSendtoken(sendtoken)
        sendtoken
        EasyHttp.post(this)
            .api(api)
            .request(object : HttpCallback<HttpData<LoginApi.DataJson>>(this) {
                override fun onSucceed(result: HttpData<LoginApi.DataJson>?) {
                    AppConfigUtils.saveToken(result?.getData()?.token)
                    AppConfigUtils.savePhone(phoneView?.text.toString())
                    AppConfigUtils.saveLoginData(result?.getData())
                    jumpMainPage()
                }

                override fun onEnd(call: Call?) {
                    super.onEnd(call)
                    commitView?.reset()
                }
            })

    }

    private fun jumpMainPage() {
        MainActivity.start(context)
        finish()
    }

    /**
     * [TextView.OnEditorActionListener]
     */
    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            // 模拟点击下一步按钮
            commitView?.let {
                if (it.isEnabled) {
                    onClick(it)
                    return true
                }
            }
        }
        return false
    }
}